package com.controller;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.Internal;
import com.pojo.Supplier;
import com.pojo.SysRole;
import com.pojo.SysUser;
import com.service.SysRoleService;
import com.service.SysUserService;
import com.util.Page;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private static Logger logger=Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String doLogin(Model model, HttpSession session, String account, String password){
       SysUser sysUser= sysUserService.login(account,password);
        if(sysUser==null){
            //登录失败
            model.addAttribute("error","账号或密码错误!");
            return "login";
        }

        //登陆成功
        session.setAttribute("USER_SESSION",sysUser);
        return "frame";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //移除当前登录的账号信息
        session.removeAttribute("USER_SESSION");
        // 销毁Session会话
        session.invalidate();
        return "redirect:/user/login";
    }
    /**
     * 捕获异常信息，设置到作用域，跳转到统一异常处理画面
//     * @param e
//     * @param request
     * @return
     */
//    @ExceptionHandler
//    public String handlerException(RuntimeException e, HttpServletRequest request){
//        request.setAttribute("error",e.getMessage());
//        return "login";
//    }
    
    @RequestMapping("/list")
    public String getUserList(Model model,String queryRealName,String queryRoleName,@RequestParam(defaultValue = "1") int pageIndex){
        List<SysUser> userList=null;
        Page<SysUser> sysUserPage = new Page<SysUser>();
        try {
            //设置总数据量
            sysUserPage.setTotalPage(sysUserService.count(queryRealName, queryRoleName));
            //设置总页数
            sysUserPage.setTotalPageSize();
            //当前页
            sysUserPage.setPageIndex(pageIndex);
            //获取当前页数据
            sysUserPage.setList(sysUserService.getUserList(queryRealName, queryRoleName, sysUserPage.getPageIndex(), sysUserPage.getPageSize()));

            userList=sysUserService.getUserList(queryRealName,queryRoleName,sysUserPage.getPageIndex(),sysUserPage.getPageSize());
            model.addAttribute("userList",userList);

            List<SysRole> roleList=null;
            roleList=sysRoleService.roleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleName", queryRoleName);
            model.addAttribute("userList", sysUserPage.getList());

            model.addAttribute("totalPageCount", sysUserPage.getTotalPageSize());
            model.addAttribute("totalCount", sysUserPage.getTotalPage());
            model.addAttribute("currentPageNo", sysUserPage.getPageIndex());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("供货商列表接口访问失败!");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }
    
    @RequestMapping("/toAdd")
    public String toAA(){
        return "sysUser/add";
    }

    @RequestMapping("/add")
    public String add(SysUser sysUser){
        if(sysUserService.add(sysUser)){
            return "redirect:/sysUser/list";
        }
        return "sysUser/add";
    }

    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "sysUser/updatePassword";
    }

    @RequestMapping("/savePassword")
    public String savePassword(HttpServletRequest request){
        if(request.getSession().getAttribute("USER_SESSION")==null){
            System.out.println("用户信息丢失请重新输入!");
        }
        int id=((SysUser)request.getSession().getAttribute("USER_SESSION")).getId();
        String newPassword=request.getParameter("newPassword");
        if(sysUserService.getUpdatePwd(id,newPassword)>0){
            System.out.println("修改成功!");
            request.removeAttribute("USER_SESSION");
            request.getSession().invalidate();
            return "login";
        }else {
            System.out.println("修改密码失败!");
            return "frame";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/checkOldPassword/{oldPassword}",produces = {"application/json;charset=UTF-8"})
    public String checkOldPassword(HttpServletRequest request,@PathVariable String oldPassword){
        int id=((SysUser)request.getSession().getAttribute("USER_SESSION")).getId();
        logger.info("密码是否正确:"+oldPassword);
        String pwdJSON=null;
        if(request.getSession().getAttribute("USER_SESSION")==null){
            pwdJSON="sessionerror";
            logger. info("用户session过期!");
        }
        if(oldPassword==null||oldPassword.equals("")){
            pwdJSON="error";
            logger.info("旧密码为空!");
        }
        if(sysUserService.checkOldPwd(id,oldPassword)>0){
            pwdJSON="true";
        }else{
            pwdJSON="false";
        }
        return JSON.toJSONString(pwdJSON);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}/view",produces = {"application/json;charset=UTF-8"})
    public Object view(@PathVariable String id){
        logger.debug("根据id查询用户详情id:"+id);
        SysUser sysUser=null;
        try {
            sysUser=sysUserService.getUserById(id);
            logger.debug("查询到用户信息:"+sysUser);
        }catch (Exception e){
            e.printStackTrace();
            return "failed";
        }
        return JSON.toJSONString(sysUser);
    }

    @ResponseBody
    @RequestMapping("/del/{id}")
    public String del(@PathVariable String id){
        if(sysUserService.del(id)){
            return JSON.toJSONString(true);
        }else{
            return JSON.toJSONString(false);
        }
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam String uid,Model model){
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }
}

